from io import BytesIO
import base64
import re
from PIL import Image
import numpy as np


def image_to_base64(img):
    if isinstance(img, np.ndarray):
        img = Image.fromarray(img.astype('uint8')).convert('RGB')
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = base64.b64encode(byte_data)
    return base64_str.decode()


def base64_to_image(base64_str):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    return img

def save_iamge(filename, img):
    img.save(file)